import { Modal, Form } from 'antd'
import { Rule } from 'antd/lib/form'
import React, { useEffect } from 'react'
import { Add, Update } from '../../api/api'
import HomeStore from '../../stores/HomeStory'

import { inject, observer } from 'mobx-react'

import '../../config/dark-theme.less'
import { randomInt } from 'crypto'
export interface ModalPlusProps {
  HomeStore: HomeStore
  visible: boolean
  setVisible: React.Dispatch<React.SetStateAction<boolean>>
  url?: string
  title?: string
  recode?: any
  columns?: ModalPlusColumns[]
  method?: 'post' | 'put'
}

export interface ModalPlusColumns {
  key: string
  type: any
  remark?: string
  rules?: Rule[] | undefined
  title: string
}

const ModalPlus: React.FC<ModalPlusProps> = (props: ModalPlusProps) => {
  const { method, title, visible, recode, columns, setVisible, url } = props
  const [modalForm] = Form.useForm()

  useEffect(() => {
    modalForm.setFieldsValue(recode)
  }, [modalForm, recode])

  const handleOk = () => {
    let editParams = ''
    modalForm
      .validateFields()
      .then((val) => {
        for (let key in val) {
          if (val[key] !== undefined) {
            editParams += '&' + key + '=' + val[key]
          }
        }
        if (!!url) {
          if (method === 'post') {
            editParams += '&userId=' + randomInt(10000 * 10000)
            Add(url, editParams)
          } else {
            editParams += '&id=' + recode.id
            Update(url, editParams)
          }
        }
        modalForm.resetFields()
        setVisible(false)
      })
      .catch((info) => {})
  }

  const handleCancel = () => {
    setVisible(false)
    modalForm.resetFields()
  }

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <Form form={modalForm}>
        {columns?.map((item: ModalPlusColumns, index) => (
          <Form.Item
            key={index}
            name={item.key}
            label={item.title}
            rules={item.rules}
          >
            <item.type
              key={index}
              placeholder={item.remark}
              autoComplete='off'
            />
          </Form.Item>
        ))}
      </Form>
    </Modal>
  )
}

export default inject('HomeStore')(observer(ModalPlus))
